package com.loongtech.bi.action.advertisment;

import com.loongtech.bi.advertisment.controller.BaseAdvAction;
import com.loongtech.bi.advertisment.model.ActiveTranData;
import com.loongtech.bi.advertisment.model.GroupDetailData;
import com.loongtech.bi.advertisment.model.NewRemainData;
import com.loongtech.bi.advertisment.service.AdvDayDataGroupService;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.core.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * ClassName: AdvDayDataAction
 * 
 * @Description: 市场数据分析 —— 广告日数据（分渠道）
 * @author liuchen
 * @date 2016-11-30 下午2:23:49
 */
@Controller
@Scope("prototype")
@RequestMapping("/market/advDayDataGroupMarket")
public class AdvDayDataGroupBiAction extends BaseAdvAction {
	private static final long serialVersionUID = 1L;
	@Resource(name = "advDayDataGroupService")
	private AdvDayDataGroupService service;

    @Autowired
    private SysUserManager sysUserManager;

	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, @RequestParam String uid, String callback) {
		try {
            Map<String, Object> result = new HashMap<String, Object>();
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

			result.put("res", "0");
			result.put("surl", getId());
			result.put("affiliation", getAffiliation());
			result.put("channelName", getChannelName());
			result.put("agent", getAgent());
			result.put("platform", getPlatform());
			result.put("paytype", getPaytype());
			result.put("advPosition", getAdvPosition());
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	private List<ActiveTranData> activeTranDatas;
	private List<NewRemainData> newRemainDatas;
	private List<List<Object>> totalPayDatas;

	private List<GroupDetailData> channelDetailDatas;
	private List<GroupDetailData> activityDetailDatas;
	private List<GroupDetailData> platformDetailDatas;
	private List<GroupDetailData> agentDetailDatas;
	private List<GroupDetailData> paytypeDetailDatas;

	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String sday,
			@RequestParam String eday, @RequestParam String agent, @RequestParam String platform,
			@RequestParam String affiliation, @RequestParam String channelName, @RequestParam String paytype,
			@RequestParam String advPosition, @RequestParam String uid, String callback) {
		try {
            Map<String, Object> result = new HashMap<String, Object>();
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

			if (hasAgents == null || hasAgents.size() <= 0) {
				result.put("res", "1");
				result.put("msg", "此用户无任何代理商权限，请联系管理员配置!");
				printToJson(response, result, callback);
				return;
			}

			activeTranDatas = new ArrayList<ActiveTranData>();
			newRemainDatas = new ArrayList<NewRemainData>();
			totalPayDatas = new ArrayList<List<Object>>();

			channelDetailDatas = new ArrayList<GroupDetailData>();
			activityDetailDatas = new ArrayList<GroupDetailData>();
			platformDetailDatas = new ArrayList<GroupDetailData>();
			agentDetailDatas = new ArrayList<GroupDetailData>();
			paytypeDetailDatas = new ArrayList<GroupDetailData>();

            String[] affiliations = "".equals(affiliation) ? getAffiliation().toArray(new String[getAffiliation().size()]) : Utils.matchesString(affiliation).split(",");
            String[] channelNames = "".equals(channelName) ? getChannelName().toArray(new String[getChannelName().size()]) : Utils.matchesString(channelName).split(",");
            String[] agents = "".equals(agent) ? getAgent().toArray(new String[getAgent().size()]) : Utils.matchesString(agent).split(",");
            String[] platforms = "".equals(platform) ? getPlatform().toArray(new String[getPlatform().size()]) : Utils.matchesString(platform).split(",");
            String[] paytypes = "".equals(paytype) ? getPaytype().toArray(new String[getPaytype().size()]) : Utils.matchesString(paytype).split(",");
            String[] advPositions = "".equals(advPosition) ? getAdvPosition().toArray(new String[getAdvPosition().size()]) : Utils.matchesString(advPosition).split(",");

            activeTranDatas = service.getActiveTranDatas(sday, eday, affiliations, channelNames, agents, platforms,
					paytypes, advPositions);
			List<List<String>> stotalPayDatas = service.getTotalPayDatas(sday, eday, affiliations, channelNames,
					agents, platforms, paytypes, advPositions);
			for (List<String> ls : stotalPayDatas) {
				List<Object> lo = new ArrayList<Object>();
				for (int i = 0; i < ls.size(); i++) {
					if (i < 5) {
						if (i != 1 && i != 2) {
							lo.add(ls.get(i));
						}
					} else {
						lo.add(Integer.valueOf(ls.get(i)));
					}
				}
				totalPayDatas.add(lo);
			}
			newRemainDatas = service.getNewRemainDatas(sday, eday, affiliations, channelNames, agents, platforms,
					paytypes, advPositions);

			channelDetailDatas = service.getChannelDetailDatas(sday, eday);
			activityDetailDatas = service.getActivityDetailDatas(sday, eday);
			platformDetailDatas = service.getPlatformDetailDatas(sday, eday);
			agentDetailDatas = service.getAgentDetailDatas(sday, eday);
			paytypeDetailDatas = service.getPaytypeDetailDatas(sday, eday);

			result.put("res", "0");
			result.put("activeTranDatas", activeTranDatas);
			result.put("totalPayDatas", totalPayDatas);
			result.put("newRemainDatas", newRemainDatas);
			result.put("channelDetailDatas", channelDetailDatas);
			result.put("activityDetailDatas", activityDetailDatas);
			result.put("platformDetailDatas", platformDetailDatas);
			result.put("agentDetailDatas", agentDetailDatas);
			result.put("paytypeDetailDatas", paytypeDetailDatas);
			ActiveTranData data = getTotal(sday, eday, affiliations, channelNames, agents, platforms, paytypes,
					advPositions);
			result.put("Totals", data);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	public ActiveTranData getTotal(String sday, String eday, String[] affiliation, String[] channelName,
			String[] agent, String[] platform, String[] paytype, String[] advPosition) {
		ActiveTranData data = new ActiveTranData();
		data.setDateStr("Totals");
		data.setClkEquipment(getSumClkEquipment());
		data.setActEquipment(getSumActEquipment());
		data.setNewActive(getSumNewActive());
		data.setNewEquipment(getSumNewEquipment());
		data.setNewAccount(getSumNewAccount());
		data.setNewPay(getSumNewPay());
		data.setNewPayUser(getSumNewPayUser());
		data.setPayrate(Double.valueOf(getSumPayrate()));
		data.setDiscount(getSumDiscount());
		data.setCpa(Double.valueOf(getSumCpa()));
		data.setTotalpay(getSumTotalpay());
		data.setRoi(Double.valueOf(getSumRoi(sday, eday, affiliation, channelName, agent, platform, paytype,
				advPosition)));
		return data;
	}

	private Integer getSumClkEquipment() {
		int total = 0;
		for (ActiveTranData a : activeTranDatas) {
			total += a.getClkEquipment();
		}
		return total;
	}

	private Integer getSumActEquipment() {
		int total = 0;
		for (ActiveTranData a : activeTranDatas) {
			total += a.getActEquipment();
		}
		return total;
	}

	private Integer getSumNewActive() {
		int total = 0;
		for (ActiveTranData a : activeTranDatas) {
			total += a.getNewActive();
		}
		return total;
	}

	private Integer getSumNewEquipment() {
		int total = 0;
		for (ActiveTranData a : activeTranDatas) {
			total += a.getNewEquipment();
		}
		return total;
	}

	private Integer getSumNewAccount() {
		int total = 0;
		for (ActiveTranData a : activeTranDatas) {
			total += a.getNewAccount();
		}
		return total;
	}

	private Integer getSumNewPay() {
		int total = 0;
		for (ActiveTranData a : activeTranDatas) {
			total += a.getNewPay();
		}
		return total;
	}

	private String getSumPayrate() {
		DecimalFormat df = new DecimalFormat("#.##");
		int totalPayUser = 0;
		int totalNewUser = 0;
		for (ActiveTranData a : activeTranDatas) {
			totalPayUser += a.getNewPayUser();
			totalNewUser += a.getNewAccount();
		}
		return totalNewUser != 0 ? df.format((double) totalPayUser / totalNewUser) : "0";
	}

	private Integer getSumDiscount() {
		Integer total = 0;
		for (ActiveTranData a : activeTranDatas) {
			total += a.getDiscount();
		}
		return total;
	}

	private Integer getSumNewPayUser() {
		int total = 0;
		for (ActiveTranData a : activeTranDatas) {
			total += a.getNewPayUser();
		}
		return total;
	}

	private String getSumCpa() {
		DecimalFormat df = new DecimalFormat("#.##");
		double totalDiscount = 0.0;
		int totalNewUser = 0;
		for (ActiveTranData a : activeTranDatas) {
			totalDiscount += a.getDiscount();
			totalNewUser += a.getNewAccount();
		}
		return totalNewUser != 0 ? df.format((double) totalDiscount / totalNewUser) : "0";
	}

	private int getSumTotalpay() {
		int totalpay = 0;
		for (ActiveTranData a : activeTranDatas) {
			totalpay += a.getTotalpay();
		}
		return totalpay;
	}

	private String getSumRoi(String sday, String eday, String[] affiliation, String[] channelName, String[] agent,
			String[] platform, String[] paytype, String[] advPosition) {
		DecimalFormat df = new DecimalFormat("#.##");
		Integer total = 0;
		for (ActiveTranData a : activeTranDatas) {
			total += a.getDiscount();
		}
		Integer roi = 0;
		try {
			roi = service.getAllRoi(sday, eday, affiliation, channelName, agent, platform, paytype, advPosition);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return total != 0 ? df.format((double) roi * 100 / total) : "0";
	}
}
